// import router from '../router';
import Vue from 'vue';
import HTTP from '../http';

export default {
  namespaced: true,
  state: {
    newProjectName: null,
    projects: [],
    currentProject: null,
    deleteError: null,

  },
  actions: {
    fetchProjects({ commit, state }) {
      return HTTP().get('/projects')
        .then(({ data }) => {
          commit('setProjects', data);
        });
    },
    createProject({ commit, state }) {
      return HTTP().post('/projects', {
        title: state.newProjectName,
      })
        .then(({ data }) => {
          commit('appendProject', data);
          commit('setNewProjectName', null);
        });
    },
    saveProject({ commit }, project) {
      return HTTP().patch(`/projects/${project.id}`, project)
        .then(() => {
          commit('unsetEditMode', project);
        });
    },
    deleteProject({ state, commit }, project) {
      commit('setDeleteError', null);
      return HTTP().delete(`/projects/${project.id}`)
        .then(() => {
          commit('removeProject', project);
          if (state.currentProject != null && project.id === state.currentProject.id) {
            commit('setCurrentProject', null);
          }
        }).catch((e) => {
          console.log(e);
          commit('setDeleteError', 'An error occured when you try to delete the project, you may try to delete all tasks of this project first!');
        });
    },
  },
  getters: {
  },
  mutations: {
    setCurrentProject(state, project) {
      state.currentProject = project;
      state.deleteError = null;
    },
    setNewProjectName(state, name) {
      state.newProjectName = name;
    },
    appendProject(state, project) {
      state.projects.push(project);
    },
    setProjects(state, projects) {
      state.projects = projects;
    },
    setProjectTitle(state, { project, title }) {
      project.title = title;
    },
    setEditMode(state, project) {
      Vue.set(project, 'isEditMode', true);
    },
    unsetEditMode(state, project) {
      Vue.set(project, 'isEditMode', false);
    },
    removeProject(state, project) {
      state.projects.splice(state.projects.indexOf(project), 1);
    },
    setDeleteError(state, error) {
      state.deleteError = error;
    },
  },
};
